from datetime import datetime, timedelta
import hashlib
import random
import string

# 模拟的用户数据库
users_db = {
    'user1': {'password': 'password123', 'email': 'user1@example.com', 'phone': '1234567890'},
    # 更多用户...
}

# 保存用户状态
user_status = {}

# 密码哈希函数
def hash_password(password):
    return hashlib.sha256(password.encode()).hexdigest()

# 生成随机验证码
def generate_code(length=6):
    return ''.join(random.choices(string.digits, k=length))

# 基于账号和密码的登录
def login_with_password(username, password):
    if username not in users_db:
        return "Invalid username"

    hashed_password = hash_password(password)
    if users_db[username]['password'] != hashed_password:
        if 'failed_attempts' not in user_status.get(username, {}):
            user_status[username] = {'failed_attempts': 0, 'last_attempt_time': datetime.now()}
        user_status[username]['failed_attempts'] += 1

        # 检查失败尝试次数
        if user_status[username]['failed_attempts'] > 3:
            return "Account locked due to too many failed attempts"

        return "Incorrect password"

    return "Login successful"

# 基于邮箱的登录
def login_with_email(email):
    for username, info in users_db.items():
        if info.get('email') == email:
            return f"Email login link sent to {email}"
    return "Email not found"

# 基于手机验证码的登录
def login_with_phone(phone):
    for username, info in users_db.items():
        if info.get('phone') == phone:
            verification_code = generate_code()
            user_status[username] = {'verification_code': verification_code, 'last_code_sent': datetime.now()}
            return f"Verification code sent to {phone}"
    return "Phone number not found"

# 模拟微信登录
def login_with_wechat(wechat_id):
    if wechat_id in users_db:
        return "WeChat login successful"
    return "WeChat account not bound"

# 检查登录会话超时
def check_session_timeout(username, max_duration_minutes=30):
    if username in user_status:
        last_attempt_time = user_status[username].get('last_attempt_time', datetime.now())
        if datetime.now() - last_attempt_time > timedelta(minutes=max_duration_minutes):
            return "Session has timed out"
    return "Session is active"

# 示例登录调用
print(login_with_password('user1', 'password123'))
print(login_with_email('user1@example.com'))
print(login_with_phone('1234567890'))
print(login_with_wechat('wechat_user1'))
print(check_session_timeout('user1'))